import { Component, OnInit, ViewChild } from '@angular/core';
import { _HttpClient } from '@delon/theme';
import { environment } from '@env/environment';
import { DatePipe } from '@angular/common';
import { ActivatedRoute } from '@angular/router';
import { StatusFollowService } from '@core/statusFollow.service';
import { LocalStorage } from '@core/local.storage';
import { NzMessageService, NzModalService, NzTreeSelectComponent } from 'ng-zorro-antd';
import { ReuseTabService } from '@delon/abc';
import { SplcService } from './splc.service';
import { DomSanitizer } from '@angular/platform-browser';

@Component({
  selector: 'app-splc.component',
  templateUrl: './splc.component.html',
  styleUrls: ['./splc.component.less']
})

export class SplcComponent implements OnInit {

  queryParam: any = {};
  tableData = []
  pageType: any;
  pageSize = '20';
  pageTotal = 0;
  pageIndex = 1;
  statusList = [];
  detailParams: any;
  loading = false;
  editor: any = {};
  doc: any = {};
  wcqk: any = {};
  bmNodes = [];
  gzxmList: any = [];
  lockHeadScroll = { y: `${window.innerHeight - 310}px` };
  mode: any;
  wdlx: any = []; // 文档类型
  iframeSrc: any;
  leaders: any = [];
  saveParam: any = {};
  allBmNodes: any = [];
  @ViewChild('bmTree', { static: false }) bmTree: NzTreeSelectComponent;
  docLevel: { 0: string; 1: string; 3: string; };
  buttonCfg: any = {};
  userInfo: any = {};
  optConfig: any = {};


  constructor(
    private datePipe: DatePipe,
    private activatedRoute: ActivatedRoute,
    public statusFollowService: StatusFollowService,
    private reuseTabService: ReuseTabService,
    public message: NzMessageService,
    private ls: LocalStorage,
    private modalService: NzModalService,
    private splcService: SplcService,
    private sanitizer: DomSanitizer,
  ) { }

  ngOnInit(): void {
    const title = {
      cx: '审批流程查询',
      wh: '审批流程维护'
    }

    this.activatedRoute.params.subscribe(params => {
      this.mode = params.mode; // edit query
      this.reuseTabService.title = title[params.mode] || '审批流程';
    });
    this.initUser();
    this.initOptConfig();
    // this.initBtns();
    this.initStatus();
    this.initDocLevel();
    this.initEditor();
    this.initWcqk();
    this.initDoc();
    this.initLeaders();
    this.initBm();
    this.getWdlx();
    this.query(true);
  }
  initUser() {
    this.userInfo = JSON.parse(this.ls.get('loginInfo'));
  }
  initEditor() {
    this.editor = {
      visible: false,
      title: '',
      width: '650px',
      params: {},
      cancel: () => {
        this.editor.visible = false;
      },
    }
  }
  initWcqk() {
    this.wcqk = {
      sizeStatus: 'normal',
      visible: false,
      title: '',
      width: '1400px',
      params: {},
      btnClick: (v) => {
        this.wcqk.sizeStatus = v;
        if (v === 'max') {
          this.wcqk.width = '100vw';
        } else {
          this.wcqk.width = '1400px';
        }
      },
      cancel: () => {
        this.wcqk.visible = false;
      },
    }
  }
  initDoc() {
    this.doc = {
      openFLag: false,
      title: '',
      width: '650px',
      params: {},
      iframeSrc: '',
      getIframeSrc: () => {
        if (this.doc.openFLag === true) {
          this.doc.openFLag = false;
          return this.sanitizer.bypassSecurityTrustResourceUrl(`./assets/pageOfficeDoc/docIndex.html?url=${this.doc.iframeSrc}`);
        } else {
          return;
        }
      },
      cancel: () => {
        this.doc.visible = false;
      },
    }
  }
  initLeaders() {
    this.splcService.getLeaders().subscribe(res => {
      this.leaders = res;
      this.initBtns();
    })
  }
  initBm() {
    this.splcService.getBm().subscribe(res => {
      this.bmNodes = res.data[0];
    })
    this.splcService.getBmAll().subscribe(res => {
      this.allBmNodes = res;
    })
  }

  /**
   * 初始化状态
   * 0, 已保存（工区保存、车间保存、科室保存）
   * 1, 工区提报（工区提报到车间）
   * 2, 车间提报（车间提报工区提报的、车间提报自己新增的）
   * 3, 车间驳回（车间驳回工区提报的）
   * 4, 科室驳回（科室驳回车间提报的，科室驳回科室提报的，）
   * 5, 科室提报（科室提报自己新增的，科室提报车间提报的）
   * 6, 提报到分管领导（科室提报到分管领导）
   * 7, 分管领导驳回（分管领导驳回科室提报的）
   * 8, 分管领导同意（分管领导领导同意科室提报的，直接返回到提报科室）
   * 9, 办公室返回（办公室盖章返回到提报科室）
   * 10, 已完结（流转终结）--行背景绿色
   * a.工区没有完成任务按钮
   * b.除了已保存和已完结状态，其他状态均可以执行已完结操作
   * c.本部门提报状态的数据，本部门不能执行已完结操作
   */
  initStatus() {
    this.statusList = [
      '已保存',
      '工区提报',
      '车间提报',
      '车间驳回',
      '科室驳回',
      '科室提报',
      '提报到分管领导',
      '分管领导驳回',
      '分管领导同意',
      '办公室返回',
      '已完结',
    ]
  }
  initDocLevel() {
    this.docLevel = {
      '0': '一级',
      '1': '二级',
      '3': '三级',
    }
  }

  /**
   * 因需要判断登陆人是否为领导，故需要先查询领导才能初始化
   */
  initBtns() {
    this.buttonCfg = {
      add: false,
      edit: false,
      delete: false,
      tibao: false,
      tibaoLingdao: false,
      tongyi: false,
      bohui: false,
      fanhui: false,
      wancheng: false,
    };
    if (this.mode === 'cx') {
      if (this.userInfo.VC_ORG$ID === 'KMBUR_KMNSEG_ORG_38') {
        this.buttonCfg.delete = true;
      }
    } else {
      switch (this.userInfo.N_LEVEL) {
        case 10: //  工区
          this.buttonCfg.add = true;
          this.buttonCfg.edit = true;
          this.buttonCfg.delete = true;
          this.buttonCfg.tibao = true;
          this.buttonCfg.wancheng = true;
          break;
        case 30: // 车间
          this.buttonCfg.add = true;
          this.buttonCfg.edit = true;
          this.buttonCfg.delete = true;
          this.buttonCfg.tibao = true;
          this.buttonCfg.bohui = true;
          this.buttonCfg.wancheng = true;
          break;
        case 50:
          if (this.isUserLeader()) { // 分管领导
            this.buttonCfg.tongyi = true;
            this.buttonCfg.bohui = true;
          } else if (this.userInfo.VC_ORG$ID === 'KMBUR_KMNSEG_ORG_33') { // 办公室
            this.buttonCfg.fanhui = true;

            this.buttonCfg.add = true;
            this.buttonCfg.edit = true;
            this.buttonCfg.delete = true;
            this.buttonCfg.tibao = true;
            this.buttonCfg.tibaoLingdao = true;
            this.buttonCfg.bohui = true;
            this.buttonCfg.wancheng = true;
          } else { // 科室
            this.buttonCfg.add = true;
            this.buttonCfg.edit = true;
            this.buttonCfg.delete = true;
            this.buttonCfg.tibao = true;
            this.buttonCfg.tibaoLingdao = true;
            this.buttonCfg.bohui = true;
            this.buttonCfg.wancheng = true;
          }
          break;
      }
    }
  }

  initOptConfig() {
    const editCfg = {
      name: '修改',
      value: ['0', '3', '4', '7'],
      func: (row) => {
      },
    };
    const deleteCfg = {
      name: '删除',
      value: ['0', '3', '4', '7'],
      func: (ids) => {
        this.splcService.delete(ids).subscribe(res => {
          if (res.msg === 'Ok') {
            this.message.success('删除成功');
            this.query();
          } else {
            this.message.warning('删除失败');
          }
        })
      },
    };
    const tibaoCfg = {
      name: '提报',
      value: ['0', '1', '2', '3', '4', '5', '7', '8'],
      func: (row) => {
      },
    };

    const bohuiCfg = {
      name: '驳回',
      value: ['1', '2', '5', '6'],
      func: (row) => {

      },
    };
    const tongyiCfg = {
      name: '同意',
      value: ['6'],
      func: (row) => {

      },
    };
    const fanhuiCfg = {
      name: '盖章返回',
      value: ['5'],
      func: (row) => {

      },
    };
    const wanchengCfg = {
      name: '完成任务',
      value: ['1', '2', '3', '4', '5', '7', '8', '9'],
      func: (ids) => {
        this.splcService.finishBatch(ids).subscribe(res => {
          if (res.msg === 'Ok') {
            this.message.success('操作成功');
            this.query();
          } else {
            this.message.warning('操作失败');
          }
        })
      },
    };

    this.optConfig = {
      'edit': editCfg,
      'delete': deleteCfg,
      'tibao': tibaoCfg,
      'tibaoLingdao': tibaoCfg,
      'bohui': bohuiCfg,
      'tongyi': tongyiCfg,
      'fanhui': fanhuiCfg,
      'wancheng': wanchengCfg,
    }
  }

  selfCheck(optType, rows) {
    const res = true;
    const optName = this.optConfig[optType].name;
    switch (optType) {
      case 'edit':
        for (const row of rows) {
          if (optType === 'edit' && this.userInfo.VC_ORG$ID === 'KMBUR_KMNSEG_ORG_33' && row.status === '5') {
            return true
          } else {
            if (row.sysOrg !== this.userInfo.VC_ORG$ID) {
              this.message.warning(`您只能${optName}本部门录入的条目`);
              return false;
            }
          }
        }
        break;
      case 'delete':
        if (optType === 'delete' && this.userInfo.VC_ORG$ID === 'KMBUR_KMNSEG_ORG_38' && this.mode === 'cx') {
          return true;
        }
        for (const row of rows) {
          if (row.sysOrg !== this.userInfo.VC_ORG$ID) {
            this.message.warning(`您只能${optName}本部门录入的条目`);
            return false;
          }
        }
        break;
      case 'wancheng':
      case 'tibao':
      case 'tibaoLingdao':
        for (const row of rows) {
          if (row.currentOrg !== this.userInfo.VC_ORG$ID && row.currentOrg !== this.userInfo.VC_NUMBER) {
            this.message.warning(`您只能对处理部门为自身的条目进行该操作`);
            return false;
          }
        }
        break;
      case 'bohui':
      case 'tongyi':
        for (const row of rows) {
          if (row.sysOrg === this.userInfo.VC_ORG$ID) {
            this.message.warning(`您不能${optName}本部门录入的条目`);
            return false;
          }
        }
        break;
    }
    return res;
  }

  dateChange(v, name) {
    this.queryParam[name] = v ? this.datePipe.transform(v, 'yyyy-MM-dd') : '';
  }

  getOrderGroup(data, keyName) {
    const dataGroup = new Map();
    const tempGroup = {};
    const orderP = new Set();
    data.forEach(row => {
      const key = row[keyName];
      orderP.add(key);
      if (tempGroup[key]) {
        tempGroup[key].push(row)
      } else {
        tempGroup[key] = [row];
      }
    });
    orderP.forEach((id: string) => {
      dataGroup.set(id, tempGroup[id])
    });
    return dataGroup;
  }

  formatQueryRes(data) {
    const indexMap = ['One', 'Two', 'Three', 'Four', 'Five']
    data.forEach(row => {
      const _docNames = [];
      const _docUrls = [];
      const _docArr = [];
      for (const str of indexMap) {
        const fileName = row[`doc${str}Name`];
        const fileUrl = row[`doc${str}Url`];
        if (fileUrl) {
          _docArr.push({
            name: fileName || '',
            url: fileUrl || '',
            field: `doc${str}Url`,
            id: row.id
          });
        }
      }
      row._docArr = _docArr
    });
    return data;
  }

  formatHref(data) {
    return environment.apiBase + '/csmis' + data.fileUrl;
  }

  query(fromBeginning = false) {

    const param: any = {
      page: fromBeginning === false ? this.pageIndex : 1,
      limit: this.pageSize,
    };
    if (this.mode === 'wh') {
      param.queryType = '0';
    } else if (this.mode === 'cx') {
      param.queryType = '1'
    }
    Object.assign(param, this.queryParam);
    this.removeUselessFields(param);
    this.removePrivateFields(param);
    this.splcService.query_table(param).subscribe(res => {
      this.tableData = this.formatQueryRes(res.data);
      this.pageTotal = res.count;
    })

  }

  checkAll(v) {
    this.tableData.forEach(row => {
      row.checked = v;
    });
  }


  statusFollow(data) {
    return this.statusFollowService.init('sxdaqkk', data);
  }

  getChecked() {
    return this.tableData.filter(row => row.checked === true);
  }

  reset() {
    this.queryParam = {};
  }

  /**
   * 删除私立字段
   * @param param  1
   */
  removePrivateFields(param) {
    Object.keys(param).forEach(key => {
      if (!(key.indexOf('_'))) {
        delete param[key];
      }
    });
  }

  /**
   * 删除null字段
   * @param param 1
   */
  removeUselessFields(param) {
    Object.keys(param).forEach(key => {
      if (!param[key]) {
        delete param[key];
      }
    });
  }



  formatDate(param) {
    if (param._begindate) {
      param.begindate = this.datePipe.transform(param._begindate, 'yyyy-MM-dd');
    }
    if (param._enddate) {
      param.enddate = this.datePipe.transform(param._enddate, 'yyyy-MM-dd');
    }
  }

  showEditor(type) {
    // const titleCn = { add: '新增', edit: '修改' };
    // this.editor.title = titleCn[type];
    if (type === 'edit') {
      const checkedRows = this.getChecked();
      if (!checkedRows.length) {
        this.message.warning('请选择一条记录进行操作');
        return;
      }
      const check = this.optCheck(type, checkedRows);
      if (!check) {
        return;
      }
      this.editor.title = '修改';
      this.editor.params = {
        mode: type,
        wdlx: this.wdlx,
        row: checkedRows[0]
      }
    } else {
      this.editor.title = '新增';
      this.editor.params = {
        mode: type,
        wdlx: this.wdlx,
      }
    }

    this.editor.visible = true;

  }
  showWcqk() {
    const checked = this.getChecked();
    if (!checked.length) {
      this.message.warning('请选择一条记录进行操作');
      return;
    }
    this.wcqk.visible = true;
    this.wcqk.title = '完成情况';
    this.wcqk.params = {
      pId: checked[0].id,
      mode: this.mode,
      // sizeMode: this.wcqk.sizeStatus
    }
  }
  tagCloseAble(row) {
    let res = '';
    if (this.mode === 'cx') {
      res = 'default';
    } else {
      if (
        row.currentOrg === this.userInfo.VC_ORG$ID ||
        (row.fgleader === this.userInfo.VC_NUMBER && row.status === '6') ||
        (this.userInfo.VC_ORG$ID === 'KMBUR_KMNSEG_ORG_33' && row.status === '5')
      ) {
        res = 'closeable';
      } else {
        res = 'default';
      }
    }
    return res;
  }
  tagClose(e, doc) {
    e.preventDefault(); // 终止默认删除tag的行为
    const param = {
      id: doc.id,
    }
    param[doc.field] = doc.url;
    this.modalService.confirm({
      nzTitle: `<i>确认删除</i>`,
      nzWidth: '600',
      nzContent: '确认删除吗?',
      nzOnOk: () => {
        this.splcService.deleteDoc(param).subscribe(res => {
          if (res.msg === 'Ok') {
            this.message.success('删除成功');
            this.query();
          } else {
            this.message.warning('删除失败');
          }
        })
      },
      // nzOnCancel: () => {
      //   this.query();
      // }
    })
  }

  getWdlx() {
    this.splcService.getWdlx().subscribe(res => {
      this.wdlx = res.data;
    })
  }

  /**
   * 操作检验
   * @param optType 
   * @param checkedRows 
   */
  optCheck(optType, checkedRows) {
    let check = true;
    const optName = this.optConfig[optType].name;
    if (!checkedRows.length) {
      this.message.warning(`请先勾选条目以执行 ${optName} 操作`);
      check = false;
    } else {
      // 是否存在不可操作项 存在就返回true
      const index = checkedRows.findIndex(row => {
        if (optType === 'edit' && this.userInfo.VC_ORG$ID === 'KMBUR_KMNSEG_ORG_33' && row.status === '5') {
          return false;
        } else if (optType === 'delete' && this.userInfo.VC_ORG$ID === 'KMBUR_KMNSEG_ORG_38' && this.mode === 'cx') {
          return false;
        } else {
          const optSta = this.optConfig[optType].value;
          return !optSta.includes(row.status);
        }
      })
      // const statusList = this.jzjcTool.status.statusList;
      // const qsStaStr = optSta.map(el => statusList[el]);
      if (index !== -1) {
        this.message.warning(`您不能对该状态的条目进行${optName}操作`, { nzDuration: 3000 });
        check = false;
      }

      if (this.selfCheck(optType, checkedRows) === false) {
        return false;
      }
    }
    return check;
  }

  deleteAll() {
    // const checked = this.getChecked();
    // if (!checked.length) {
    //   this.message.warning('请选择一条记录进行操作');
    //   return;
    // }
    // this.modalService.confirm({
    //   nzTitle: `<i>确认删除</i>`,
    //   nzWidth: '600',
    //   nzContent: '确认删除吗?',
    //   nzOnOk: () => {
    //     const ids = [];
    //     checked.forEach(row => {
    //       ids.push(row.id);
    //     });
    //     this.splcService.delete(ids).subscribe(res => {
    //       if (res.msg === 'Ok') {
    //         this.message.success('删除成功');
    //         this.query();
    //       } else {
    //         this.message.warning('删除失败');
    //       }
    //     })
    //   }
    // })
    this.optAll('delete', '', '确认删除吗?')
  }



  tibao(content?) {
    // this.saveParam = {};
    this.opt('tibao', '选择部门', content);
  }

  tibaoLeader(content?) {
    // this.saveParam = {};
    this.opt('tibaoLingdao', '选择分管领导', content);
  }

  tongyi() {
    // this.saveParam = {};
    this.opt('tongyi', '', '确认进行同意操作吗？')
  }

  bohui(content) {
    // this.saveParam = {};
    this.opt('bohui', '填写意见', content)
  }

  fanhui() {
    // this.saveParam = {};
    this.opt('fanhui', '', '确认进行盖章返回操作吗？')
  }

  wancheng() {
    this.optAll('wancheng', '', '确认进行完成任务操作吗?');
  }

  optAll(type, confirmTitle?, content?) {
    const checkedRows = this.getChecked();
    if (!checkedRows.length) {
      this.message.warning('请选择一条记录进行操作');
      return;
    }
    const check = this.optCheck(type, checkedRows);
    if (!check) {
      return;
    }
    this.modalService.confirm({
      nzTitle: confirmTitle || `<i>确认</i>`,
      nzWidth: '600',
      nzContent: content || '',
      nzOnOk: () => {
        const ids = [];
        checkedRows.forEach(row => {
          ids.push(row.id);
        });
        if (this.optConfig[type].func) {
          this.optConfig[type].func.call(this, ids)
        }
      }
    })
  }

  opt(type, confirmTitle?, content?) {
    this.saveParam = {};
    const checkedRows = this.getChecked();
    if (!checkedRows.length) {
      this.message.warning('请选择一条记录进行操作');
      return;
    }
    const check = this.optCheck(type, checkedRows);
    if (!check) {
      return;
    }
    this.modalService.confirm({
      nzTitle: confirmTitle || `<i>确认</i>`,
      nzWidth: '600',
      nzContent: content || '',
      nzOnOk: () => {
        this.flow(type, checkedRows)
      }
    })
  }

  getSelectName(key, nodes, fieldName?, fieldValue?) {
    for (const node of nodes) {
      if (node[fieldName ? fieldName : 'opValue'] === key) {
        return node[fieldValue ? fieldValue : 'opName'];
      }
    }
  }

  flow(type, checkedRows) {
    const id = checkedRows[0].id;
    const status = this.getStatus(type, checkedRows[0]);
    if (this.saveParam._bm) {
      this.saveParam.targetOrg = this.saveParam._bm;
      this.saveParam.targetOrgName = this.getSelectName(this.saveParam._bm, this.bmNodes, 'ID', 'NAME');
    } else if (this.saveParam._leader) {
      this.saveParam.targetOrg = this.saveParam._leader;
      this.saveParam.targetOrgName = this.getSelectName(this.saveParam._leader, this.leaders);
    }
    const param: any = {
      status,
      targetOrg: this.saveParam.targetOrg,
      targetOrgName: this.saveParam.targetOrgName,
      pid: id
    }
    if (type === 'tibao' && this.saveParam.targetOrg === 'KMBUR_KMNSEG_ORG_33' && checkedRows[0].status !== '8') {
      this.message.warning('只有分管领导同意才能提报办公室');
      return;
    }
    if (type === 'bohui') {
      if (this.saveParam.operateSituation) {
        param.operateSituation = this.saveParam.operateSituation || '';
      } else {
        this.message.warning('请填写意见');
        return;
      }
    }
    this.splcService.flow(param).subscribe(res => {
      if (res.msg === 'Ok') {
        this.message.success('操作成功');
        this.query();
      } else {
        this.message.warning('操作失败');
      }
    })
  }

  getStatus(type, row) {
    let status = '0';
    if (type === 'wancheng') {
      status = '10';
    } else {
      switch (this.userInfo.N_LEVEL) {
        case 10: //  工区只能提报
          status = '1';
          break;
        case 30:
          switch (type) {
            case 'tibao':
              status = '2';
              break;
            case 'bohui':
              status = '3';
              break;
          }
          break;
        case 50:
          if (this.isUserLeader()) { // 分管领导
            switch (type) {
              case 'tibao':
                status = '5';
                break;
              case 'tongyi':
                status = '8';
                break;
              case 'bohui':
                status = row.status === '6' ? '7' : '4';
                break;
              default:
                break;
            }
          } else if (this.userInfo.VC_ORG$ID === 'KMBUR_KMNSEG_ORG_33') { // 办公室
            switch (type) {
              case 'fanhui':
                status = '9';
                break;
            }
          } else { // 科室
            switch (type) {
              case 'tibao':
                status = '5';
                break;
              case 'tibaoLingdao':
                status = '6';
                break;
              case 'bohui':
                status = '4';
                break;
            }
          }
          break;
      }
    }
    return status;
  }

  isUserLeader() {
    return this.leaders.some(leader => leader.opValue === this.userInfo.VC_NUMBER)
  }


  trClick(row) {
    this.checkAll(false);
    row.checked = true;
  }



  trDbclick() {

  }

  showDoc(url, row) {
    // 0 可修改 1 只读
    let canEdit = 1;
    if (this.mode !== 'cx') {
      canEdit = (
        row.currentOrg === this.userInfo.VC_ORG$ID ||
        (row.fgleader === this.userInfo.VC_NUMBER && row.status === '6') ||
        (this.userInfo.VC_ORG$ID === 'KMBUR_KMNSEG_ORG_33' && row.status === '5')
      ) ? 0 : 1;
    }
    this.doc.openFLag = true;
    this.iframeSrc = this.sanitizer.bypassSecurityTrustResourceUrl(`./assets/pageOfficeDoc/docIndex.html?url=${url}&canEdit=${canEdit}`);
  }

  showOffice() {
    window.open('./doc/docIndex.html', '_blank')
  }
}
